package com.server.modules.api.web;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.server.common.utils.HttpUtils;
import com.server.common.utils.IdGen;
import com.server.common.utils.MD5Utils;
import com.server.common.utils.StringUtils;
import com.server.modules.api.Base.BaseAppController;
import com.server.modules.api.entity.LoanEx;
import com.server.modules.api.utils.Constants;
import com.server.modules.api.vo.*;
import com.server.modules.api.vo.list.LoanList;
import com.server.modules.sys.common.StaticDefine;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.bank.Bank;
import com.server.modules.sys.entity.loan.CustomPay;
import com.server.modules.sys.entity.loan.Loan;
import com.server.modules.sys.entity.material.MaterialType;
import com.server.modules.sys.entity.material.MaterialUpload;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.entity.tag.Tag;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Author Administrator
 * Date 2016/7/26
 */
@Controller
@RequestMapping(value = "/api/loan")
public class LoanListAPIController extends BaseAppController {
	@ResponseBody
	@RequestMapping(value = "/getLoanList")
	public BaseQueryVo getLoanList(HttpServletRequest request, LoanListVo vo) {
        setPageConfig(vo);
		Loan loan = new Loan();
		loan.setTypeId(vo.getTypeId());
		loan.setPage(vo.getPage());
        List<MemberTag> memberTags = new Gson().fromJson(vo.getTags(), new TypeToken<List<MemberTag>>(){}.getType());
        if (memberTags != null && memberTags.size() > 0){
            List<MemberTag> saveTags = new ArrayList<MemberTag>();
            for (MemberTag tag : memberTags){
                tag.setId(IdGen.uuid());
                tag.setMemberId(vo.getMemberId());
                tag.setTagId(tag.getTagId());
                saveTags.add(tag);
            }
            vo.setListTags(saveTags);
        }
        //获取贷款列表
		List<Loan> loens = loanListService.getLoanList(vo);
		if (loens == null && loens.size() == 0) {
			return returnMsgAPIService.getRet(Constants.notFound);
		} else {
			vo.setRetCode(0);
			vo.setRetMsg("贷款信息获取成功");
			List<LoanEx> loanListEx = new ArrayList<LoanEx>();
			for(Loan tmpLoan :loens){
				LoanEx loanEx = new LoanEx();
				loanEx.setLoan(tmpLoan);
				Bank bank = bankService.get(tmpLoan.getBankId());
				if (bank!= null){
					//修改
					loanEx.setBankName("银行渠道");
				}

				List<Tag> loanTagses = 	tagAPIService.selectTagsByLoan(tmpLoan);
				if (loanTagses != null)
					loanEx.setTagList(loanTagses);
				loanListEx.add(loanEx);
			}
			LoanList loanList = new LoanList(loanListEx);
			vo.setData(loanList);
		}
		return vo;
	}
	@ResponseBody
	@RequestMapping(value = "/getLoanDetail")
	public BaseQueryVo getLoanDetail(HttpServletRequest request,LoanTypeListVo loanTypeListVo) {
		try {
			if (!checkLogin(loanTypeListVo)){
				return returnMsgAPIService.getRet(Constants.errLogin);
			}
		}catch (Exception e){
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		BaseQueryVo<LoanAppVO> baseQueryVo = new BaseQueryVo<LoanAppVO>();
		Loan loan = loanListService.get(loanTypeListVo.getLoanId());
		if (loan  == null){
			return returnMsgAPIService.getRet(Constants.notFound);
		}else{
			List<User> users=  userAPIService.getMembersByLoanId(loanTypeListVo);
			User user = null;
			if (users == null || users.size() == 0){
					user = userAPIService.getUserById("1");
			}else{
				user = users.get(0);
			}
					baseQueryVo.setRetCode(0);
					baseQueryVo.setRetMsg("成功");
					LoanAppVO vo  = new LoanAppVO();
					vo.setUrl(HttpUtils.getHostURL(request)+"api/loan/getLoanDetailPage?loanId="+loanTypeListVo.getLoanId()+"&sessionId="+loanTypeListVo.getSessionId());
					vo.setCsid(user.getId());
					vo.setCshxId(user.getHxUsername());
					vo.setCsName(user.getName());
			        vo.setCsPhoneNum(user.getPhone());
					//vo.setName(loan.getName());
					baseQueryVo.setData(vo);
		}
		return baseQueryVo;
	}
	@ResponseBody
	@RequestMapping(value = "/getLoanDetailPage", method = RequestMethod.GET)
	public ModelAndView getLoanDetailPage(HttpServletRequest request,LoanTypeListVo loanTypeListVo) {
		ModelAndView mv = new ModelAndView();
		Loan loan = loanListService.get(loanTypeListVo.getLoanId());
		if (loan == null){
			mv.setViewName("/error/500");
		}else{
			mv.addObject("loan",loan);
			if (loanTypeListVo.getShare() != null && loanTypeListVo.getShare().equals("1")){
				mv.setViewName("/modules/api/loan/loanDetailShare");
			}else{
				mv.setViewName("/modules/api/loan/loanDetail");
			}

		}
		return mv;
	}

	@ResponseBody
	@RequestMapping(value = "/getLoanUploadMaterial", method = RequestMethod.POST)
	public BaseQueryVo getLoanUploadMaterial(HttpServletRequest request,LoanTypeListVo loanTypeListVo) {
		try {
			if (!checkLogin(loanTypeListVo)){
				return returnMsgAPIService.getRet(Constants.errLogin);
			}
		}catch (Exception e){
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.errLogin);
		}

		BaseQueryVo baseQueryVo = new BaseQueryVo();
		List<MaterialTypeEx> list = loanListService.getMaterialTypeByLoanId(loanTypeListVo);
		if (list != null && list.size() > 0){
			baseQueryVo.setData(list);
			baseQueryVo.setRetCode(0);
			baseQueryVo.setRetMsg("查询成功");
		}else{
			baseQueryVo.setRetCode(0);
			baseQueryVo.setRetMsg("未查询到数据");
		}
		return  baseQueryVo;
	}
//查询
	@ResponseBody
	@RequestMapping(value = "/getLoanUploadMaterialDetail", method = RequestMethod.POST)
	public BaseQueryVo getLoanUploadMaterialDetail(HttpServletRequest request,LoanTypeListVo loanTypeListVo) {
		try {
			if (!checkLogin(loanTypeListVo)){
				return returnMsgAPIService.getRet(Constants.errLogin);
			}
		}catch (Exception e){
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.errLogin);
		}

		BaseQueryVo baseQueryVo = new BaseQueryVo();
		List<MaterialTypeEx> list = loanListService.getMaterialDetailById(loanTypeListVo);
		if (list != null && list.size() > 0){
			baseQueryVo.setData(list);
			baseQueryVo.setRetCode(0);
			baseQueryVo.setRetMsg("查询成功");
		}else{
			baseQueryVo.setRetCode(0);
			baseQueryVo.setRetMsg("未查询到数据");
		}
		return  baseQueryVo;
	}
	@ResponseBody
	@RequestMapping(value = "/uploadMaterial", method = RequestMethod.POST)
	public BaseQueryVo uploadMaterial(HttpServletRequest request,FileVO vo) {
		try {
			if (!checkLogin(vo)){
				return returnMsgAPIService.getRet(Constants.errLogin);
			}
		}catch (Exception e) {
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		BaseQueryVo baseQueryVo = new BaseQueryVo();
	//	List<MaterialUpload> materialUploads =loanListService.getMaterialUpload(vo);
		MaterialUpload materialUpload = new MaterialUpload();
		materialUpload.setMemberId(vo.getMemberId());
		User userBy = new User();
		userBy.setId("1");
		userBy.setCreateDate(new Date());
		materialUpload.setCreateBy(userBy);
		materialUpload.setUpdateBy(userBy);
		//2017/01/19修改groupId  手机上传的groupId统一为1  之前的groupId是为了保证上传的图片是一组 现在通过type区分，不需要了
/*		if (StringUtils.isNotEmpty(vo.getGroupID())){
			materialUpload.setGroupId(vo.getGroupID());
		}else{*/
			materialUpload.setGroupId("1");
		/*}*/
		materialUpload.setOrderBy("1");
	/*	if (materialUploads != null && materialUploads.size()>0)
			materialUpload = materialUploads.get(0);*/

		MaterialType materialType = null;
		if (StringUtils.isNotEmpty(vo.getTypeId())) {
			materialType = materialTypeService.get(vo.getTypeId());
			if (materialType == null) {
				return returnMsgAPIService.getRet(Constants.materalTypeNotFound);
			}
		}

		if (StringUtils.isEmpty(vo.getTypeId())){
			return returnMsgAPIService.getRet(Constants.incompleteData);
		}
		materialUpload.setTypeId(vo.getTypeId());
		materialUpload.setName(materialType.getName());
		if (StringUtils.isNotEmpty(materialType.getType())){
			if (materialType.getType().equals("fileselect")){
				materialUpload.setIsNewRecord(true);
				materialUpload.setId(IdGen.uuid());
				if (StringUtils.isNotEmpty(vo.getGroupID())){
					materialUpload.setGroupId(vo.getGroupID());
				}else{
					return returnMsgAPIService.getRet(Constants.incompleteData);
				}
				if (StringUtils.isNotEmpty(vo.getOrder())){
					materialUpload.setOrderBy(vo.getOrder());
				}else{
					return returnMsgAPIService.getRet(Constants.incompleteData);
				}
				try {
					MaterialUpload	tmpmaterialUpload = materialUploadService.findMaterialUploadbymd5(MD5Utils.md5Encode(vo.getImageHash()));
					if (tmpmaterialUpload != null && tmpmaterialUpload.getUrl()!=null){
						baseQueryVo.setRetCode(0);
						baseQueryVo.setRetMsg("文件已存在，不需要上传");
						materialUpload.setUrl(tmpmaterialUpload.getUrl());
						materialUpload.setMd5(tmpmaterialUpload.getMd5());
					}else {
						materialUpload.setMd5(MD5Utils.md5Encode(vo.getImageHash()));
						String filePath = fileService.saveFile(vo); //保存文件
						if (org.springframework.util.StringUtils.isEmpty(filePath)){
							return  returnMsgAPIService.getRet(Constants.saveError);
						}else{
							materialUpload.setUrl(filePath);
						}
					}
				}catch (Exception e){
					logger.error(e.getMessage());
				}
			}else{
				if (StringUtils.isNotEmpty(vo.getValue())){
					materialUpload.setValue(vo.getValue());
					try {
						materialUpload.setMd5(MD5Utils.md5Encode(vo.getValue()));
					}catch (Exception e){
						baseQueryVo.setRetCode(-1);
						baseQueryVo.setRetMsg(e.getMessage());
						return baseQueryVo;
					}
				}else{
					return returnMsgAPIService.getRet(Constants.incompleteData);
				}
			}
		}else{
			return returnMsgAPIService.getRet(Constants.incompleteData);
		}
		materialUploadAPIService.delMaterialUpload(materialUpload);//删除相同类别，不同组的数据
		materialUploadService.save(materialUpload);
		baseQueryVo.setRetCode(0);
		baseQueryVo.setRetMsg("上传成功");
		
		return  baseQueryVo;
	}
	@ResponseBody
	@RequestMapping(value = "/applyLoan", method = RequestMethod.POST)
	public BaseQueryVo applyLoan(HttpServletRequest request,ApplyLoanVO vo) {
		try {
			if (!checkLogin(vo)){
				return returnMsgAPIService.getRet(Constants.errLogin);
			}
		}catch (Exception e) {
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		Loan loan =loanService.get(vo.getLoanId());
		if (loan == null){
			//没有这个贷款
			return returnMsgAPIService.getRet(Constants.notFound);
		}
		Member member = memberService.get(vo.getMemberId());
		if (member == null){
			return returnMsgAPIService.getRet(Constants.notFoutUser);
		}
		if (!StringUtils.isNotEmpty(vo.getMemberLoanLimit())){
			return returnMsgAPIService.getRet(Constants.incompleteData);
		}
		String orderNo = new Date().getTime() + StringUtils.createOrder(7);
		CustomPay customPay = new CustomPay();
		customPay.setLoanid(vo.getLoanId());
		customPay.setMemberid(vo.getMemberId());
		customPay.setMemberName(member.getRealname());
		customPay.setMemberPhone(member.getUsername());
        String memberLoanLimit = vo.getMemberLoanLimit();
      //万转为分存
        try {
            BigDecimal memberLoanLimitBd=new BigDecimal(memberLoanLimit);
            BigDecimal abs = new BigDecimal("1000000");
             memberLoanLimit = memberLoanLimitBd.multiply(abs)+"";
        }catch (Exception e){
            e.printStackTrace();
        }
        customPay.setMemberLoanLimit(memberLoanLimit);
		customPay.setName(loan.getName());
		customPay.setOrderNum(orderNo);
		customPay.setRemarks(vo.getRemarks());
		customPay.setOrderFlag("0");//创建时未支付
		customPay.setOrigin(StaticDefine.LOAN_CUSTOM_PAY_ORIGIN.APP);// 来源0移动端 1pc端
		try {
			customPayService.save(customPay);
			LoanTypeListVo loanTypeListVo = new LoanTypeListVo();
			loanTypeListVo.setLoanId(loan.getId());
			List<User> users=  userAPIService.getMembersByLoanId(loanTypeListVo);
			User user = null;
			if (users == null || users.size() == 0){
				user = userAPIService.getUserById("1");
			}else{
				user = users.get(0);
			}
			List<String> userList = new ArrayList<String>(1);
			userList.add(user.getHxUsername());
			Map<String,String > msg = new HashedMap();
			msg.put("type","text");
			msg.put("msg","有用户正在申请你的产品，客户电话为:"+member.getTelephone());
			imService.addFriendSingle(member.getHxUsername(),userList.get(0));
			imService.sendSysMessages(userList,msg,null);
			return returnMsgAPIService.getRet(Constants.ok);
		}catch (Exception e){
			BaseQueryVo baseQueryVo = new BaseQueryVo();
			baseQueryVo.setRetCode(-1);
			baseQueryVo.setRetMsg(e.getMessage());
			return baseQueryVo;
		}
	}
	@ResponseBody
	@RequestMapping(value = "/getApplyLoanList", method = RequestMethod.POST)
	public BaseQueryVo getApplyLoanList(HttpServletRequest request,ApplyLoanVO vo) {
		try {
			if (!checkLogin(vo)) {
				return returnMsgAPIService.getRet(Constants.errLogin);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		BaseQueryVo baseQueryVo = new BaseQueryVo();
		CustomPay customPay = new CustomPay();
		customPay.setMemberid(vo.getMemberId());
		customPay.setOrderFlag(vo.getOrderFlag());
		List<ApplyLoan> applyLoanList =	applyLoanAPIService.findApplyLoanList(customPay);
		if (applyLoanList == null || applyLoanList.size() == 0){
			//app端贷款金额都是显示的memberLoanLimit  实际上审核通过后应该是loanLimit  因此 只要审核通过的的贷款都要修改memberLoanLimit为
			//loanLimit  以便app端显示
			for (ApplyLoan applyLoan : applyLoanList) {
				if(!(applyLoan.getOrderFlag().equals(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAY)||applyLoan.getOrderFlag().equals(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WAITTINGCHECK))){
					applyLoan.setMemberLoanLimit( StringUtils.isBlank(applyLoan.getLoanLimit())?applyLoan.getMemberLoanLimit(): applyLoan.getLoanLimit());
				}
			}
			return returnMsgAPIService.getRet(Constants.notFound);
		}else {
			baseQueryVo.setRetCode(0);
			baseQueryVo.setRetMsg("查询成功");
			baseQueryVo.setData(applyLoanList);
			return baseQueryVo;
		}

	}
	@ResponseBody
	@RequestMapping(value = "/delApplyLoan", method = RequestMethod.POST)
	public BaseQueryVo delApplyLoan(HttpServletRequest request,ApplyLoanVO vo) {
		try {
			if (!checkLogin(vo)) {
				return returnMsgAPIService.getRet(Constants.errLogin);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		if (!StringUtils.isNotEmpty(vo.getObjId())){
			return returnMsgAPIService.getRet(Constants.incompleteData);
		}
		CustomPay customPay = customPayService.get(vo.getObjId());
		if (customPay == null){
			return returnMsgAPIService.getRet(Constants.notFound);
		}

		BaseQueryVo baseQueryVo = new BaseQueryVo();
		if (customPay.getOrderFlag().equals("1")){
			baseQueryVo.setRetCode(-1);
			baseQueryVo.setRetMsg("已付款的交易不可以删除");
			return baseQueryVo;
		}
		try {
			customPayService.delete(customPay);
			return returnMsgAPIService.getRet(Constants.ok);
		}catch (Exception e){
			baseQueryVo.setRetCode(-1);
			baseQueryVo.setRetMsg(e.getMessage());
			return baseQueryVo;
		}
	}
	@ResponseBody
	@RequestMapping(value = "/getMaterialTypeName", method = RequestMethod.GET)
	public ModelAndView getMaterialTypeName(){
		ModelAndView mv = new ModelAndView();
		List<MaterialType> materialTypes = 	materialUploadAPIService.getMaterialTypeName();
		mv.addObject("materialTypes",materialTypes);
		mv.setViewName("/modules/api/Loanfilter/example/index");
		return mv;
	}


	@RequestMapping(value = "/getLoanListFilter", method = RequestMethod.GET)
	public ModelAndView getLoanListFilter(String ids){

//		List<Integer> indexList =  JSON.parseArray(ids, Integer.class);
		String[] newstr  = ids.split(",");
		List<String> stringList = new ArrayList<>();
		for (int i = 0;i < newstr.length;i++){
			stringList.add(newstr[i]);
		}

		ModelAndView mv = new ModelAndView();
		List<LoanDto> loans = materialUploadAPIService.getMaterialTypeLoan(stringList);
		if(loans.size() == 0){
//			mv.addObject("loans",loans);
			mv.setViewName("/modules/api/Loanfilter/example/layout0");
		}
		else {
			mv.addObject("loans", loans);
			mv.setViewName("/modules/api/Loanfilter/example/layout");
		}
		return mv;
	}

}
